package com.example.hybridmobiledemo.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.hybridmobiledemo.bean.SHSQLInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MySQLHelper$
 * @Description: 作用
 * @Author: letquit
 * @CreateDate: 23/10/2021$
 * @Version: 1.0
 */
public class MyDataAdapter {
    private SearHistorySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;

    public void openDB(Context context) {
        openHelper = new SearHistorySQLiteOpenHelper(context, "SHDB.db", null, 1);
        try {
            database = openHelper.getWritableDatabase();
        } catch (Exception e) {
            database = openHelper.getReadableDatabase();
        }
    }

    public void closeDB() {
        if (database != null) {
            database.close();
            database = null;
        }
        if (openHelper != null) {
            openHelper.close();
            openHelper = null;
        }
    }

    public List<SHSQLInfo> Query(Context context, int mId) {
        List<SHSQLInfo> cartList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("SearHis", null, null,
                null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(0);
                String carId = cursor.getString(1);
                if (mId == id) {
                    cartList.add(new SHSQLInfo(carId));
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return cartList;
    }

    public List<SHSQLInfo> QueryAll(Context context) {
        List<SHSQLInfo> cartList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("SearHis", null, null,
                null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                String carId = cursor.getString(1);
                cartList.add(new SHSQLInfo(carId));
            } while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return cartList;
    }

    public long insert(Context context, SHSQLInfo info) {
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("content", info.getContent());
        long result = database.insert("SearHis", null, values);
        closeDB();
        return result;
    }

    public int delete(Context context, String id) {
        openDB(context);
        int result = database.delete("SearHis", "commodityId=?", new String[]{id});
        closeDB();
        return result;
    }

    public void deleteAll(Context context) {
        openDB(context);
        database.execSQL("delete from SearHis");
        closeDB();
    }
}
